import routes from '../routes/index'

const go = (url, t) => {
  let type = t ? t : 1
  if (type === 1) {
    wx.navigateTo({
      url: url
    })
  } else if (type === 2) {
    wx.redirectTo({
      url: url
    })
  } else if (type === 3) {
    wx.navigateBack({
      delta: url
    })
  } else if (type === 4) {
    wx.reLaunch({
      url: url
    })
  } else if (type === 5) {
    wx.switchTab({
      url: url
    })
  }
}

/**
 * 页面 & 小程序页面的统一跳转
 * @description a.以 @self: 开头的 url 跳转小程序页面； b.以 @wap: 开头的 url 跳转 wap 页面
 * @param {string} url - 跳转 url，支持跳转小程序页面和 wap 页面
 * @param {string} navigationType - 跳转类型，详见微信小程序开发文档
 * @returns {void}
 */
export const uniGoto = (url, navigationType = 'navigateTo') => {
  const miniProgramReg = /^@self:(.*)$/i
  const wapReg = /^@wap:(https?:\/{2}.*)$/i

  const miniProgramResult = miniProgramReg.exec(url)
  const wapResult = wapReg.exec(url)

  let _url = ''

  if (miniProgramResult) {
    _url = miniProgramResult[1]
  } else if (wapResult) {
    _url = `${routes.Wap}?url=${wapResult[1]}`
  } else {
    return console.error(`invalid url:: ${url}`)
  }

  wx[navigationType]({ url: _url })
}

/**
 * 检测是否为字符串
 * @param {*} v
 * @returns {boolean}
 */
export const isStr = v => typeof v === 'string'

/**
 * 检测是否为函数
 * @param {*} v
 * @returns {boolean}
 */
export const isFunc = v => typeof v === 'function'

/**
 * 检测是否为普通对象
 * @param {*} v
 * @returns {boolean}
 */
export const isPlainObject = v => v instanceof Object

/**
 * 对象属性扩展
 * @param object
 * @param sources
 * @returns {*}
 * @example defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }) => { 'a': { 'b': 2, 'c': 3 } }
 */
export const defaultsDeep = (object, ...sources) => {
  sources.forEach(source => {
    for (let k in source) {
      if (!object.hasOwnProperty(k)) {
        object[k] = source[k]
      } else if (typeof object[k] === 'object' && object[k] !== null) {
        defaultsDeep(object[k], source[k])
      }
    }
  })
  return object
}

/**
 * 确保 string 末尾有 '/'
 * @param str {string}
 * @returns {string}
 */
export const ensureTailHasSlash = str => /.*\/$/.test(str) ? str : str + '/'

/**
 * 确保 string 开头没有 '/'
 * @param str {string}
 * @reutrns {string}
 */
export const ensureCapitalHasNotSlash = str => /^\/.*/.test(str) ? str.slice(1) : str

export default {
  go,
  uniGoto,
  isStr,
  isFunc,
  isPlainObject,
  defaultsDeep,
  ensureCapitalHasNotSlash,
  ensureTailHasSlash,
}